# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render,render_to_response
from forms import FileForm
from django.http import HttpResponse
from .models import FileModel
import os
import json
from M2Crypto.EVP import Cipher
from base64 import b64encode, b64decode

# Create your views here.

iv = "0123456789abcdeffedcba9876543210"
passKey = "password4virtfannaftriv4drowssap"

def __cipher(msg, op):
    cipher = Cipher(alg='aes_128_cbc', key=passKey, iv=iv, op=op)
    v = cipher.update(msg)
    v = v + cipher.final()
    del cipher
    return v

def encrypt(msg):
    return b64encode(__cipher(msg, 1))

def decrypt(msg):
    return __cipher(b64decode(msg), 0)

def encrypt_to_file(msg, f):
    file(f, 'w').write(encrypt(msg))

def decrypt_from_file(f):
    return decrypt(file(f).read().strip())


# def register(request):
#     if request.method == 'POST':
#         uf = UserForm(request.POST,request.FILES)
#         if uf.is_valid():
#             headImg = uf.cleaned_data['headImg']
#             #这里写入数据库
#             user = UserModel()
#             user.headImg = headImg
#             user.save()
#
#             return HttpResponse('upload ok!')
#     else:
#         uf = UserForm()
#     return render_to_response('index.html',{'uf':'uf'})

#//ajax上传
# def scene_update_view(request):
#     if request.method == "POST":
#             name = request.POST.get('name')
#             status = 0
#             result = "Error!"
#             return HttpResponse(json.dumps({
#                 "status": status,
#                 "result": result
#             }))


def license(request):
    if request.method == 'GET':
        return render(request,'index.html')
    else:
    #获取表单信息

        print '**********************************'
        days = request.POST.get("days",None)
        filename = request.FILES.get("filename",None)
        macs = request.POST.get('macs',None)
        print days,filename,macs
        # print '+'*10
        # obj=request.FILES.items()
        # print obj
        # name,srcf = request.FILES.items()[0]
        # print srcf
        print 'macs=%s'% macs
        print len(macs)
        time = int(days)
    #只传递文件的情况

        if len(macs)==0:
            print '*++++++++++*'

            fpath = "/tmp/%s" % filename
            f = open(fpath.encode("utf-8"), 'w')
            for chunk in filename.chunks():
                f.writelines(chunk)
            f.close()
            # f = open(filename, 'r')
            l = open('/tmp/license.txt', 'w')
            f = open(fpath,'r')
            # with open(filename.encode("utf-8"),'r') as f:
            for mac in f.readlines():
                content = mac.strip() + ',' + str(time)
                message = encrypt(content)
                print "+"*10
                print message
                l.write('%s\n' % message)
            l.close()
            f.close()
            # return HttpResponse(u'提交正确')
            return HttpResponse(json.dumps({'code':'True','message':'Done'}))
        #传递macs的情况
        else:

                # l = open('license.txt', 'w')
            content = macs.strip() + ',' + str(time)
            message = encrypt(content)
            print "~" * 10
            print message
            context={
                'message':message
            }
            return render(request,'index.html',context=context)
                # 第一种方式直接返回一个页面展示license
            # return HttpResponse(message)
                # l.write('%\n' % message)
                # l.close()

    # else:
    #     uf = FileForm()
        return HttpResponse(u'提交错误')
    # if form.is_valid():
    #     print request.POST
    #     myFile = form.cleaned_data.get("file", None)  # 获取上传的文件，如果没有文件，则默认为None
    #     day = form.cleaned_data.get("days",None)
    #     macs = form.cleaned_data.get("macs",None)
    #     print myFile ,day,macs
    #     #写入数据库
    #     lic = FileModel()
    #     lic.filename = myFile
    #     lic.day = day
    #     lic.macs = macs
    #     lic.save()
    #     return HttpResponse('upload ok!')




#
#
# def mgmt_files(request): #列出树形目录，上传文件页面
#     if request.method == 'POST':
#         path_root = "D:\\py\\ITFiles" #上传文件的主目录
#         myFile =request.FILES.get("file", None)    # 获取上传的文件，如果没有文件，则默认为None
#         if not myFile:
#             dstatus = "请选择需要上传的文件!"
#         else:
#             path_ostype = os.path.join(path_root,request.POST.get("ostype"))
#             path_dst_file = os.path.join(path_ostype,myFile.name)
#             # print path_dst_file
#             if os.path.isfile(path_dst_file):
#                 dstatus = "%s 已存在!"%(myFile.name)
#             else:
#                 destination = open(path_dst_file,'wb+')    # 打开特定的文件进行二进制的写操作
#                 for chunk in myFile.chunks():      # 分块写入文件
#                     destination.write(chunk)
#                 destination.close()
#                 dstatus = "%s 上传成功!"%(myFile.name)
#         return HttpResponse(str(dstatus))
#
#     return render(request,'sinfors/mgmt_files.html')
#
# from django.shortcuts import render,HttpResponse
#
# # Create your views here.
# def index(request):
#     return render(request,'index.html')

